/*
 * timer.c
 *
 *  Created on: Apr 16, 2013
 *      Author: locpx
 */
#include "defines.h"
#include "extglobals.h"
#include <sys/timeb.h>
#include "stdio.h"

// start the timer
void initTimer(TIMER *timer)
{
	if (!timer->running)
	{
		timer->running = TRUE;
		ftime(&timer->startBuffer);
		timer->startTime = timer->startBuffer.time * 1000 + timer->startBuffer.millitm + timer->stopTimeDelta;
	}

	return;
}

// stop the timer
void stopTimer(TIMER *timer)
{
	if (timer->running)
	{
		timer->running = FALSE;
		ftime(&timer->stopBuffer);
		timer->stopTime = timer->stopBuffer.time * 1000 + timer->stopBuffer.millitm;
		timer->stopTimeDelta = timer->startTime - timer->stopTime;
	}

	return;
}

// reset the timer
void resetTimer(TIMER *timer)
{
	if (timer->running)
	{
		ftime(&timer->startBuffer);
		timer->startTime = timer->startBuffer.time * 1000 + timer->startBuffer.millitm;
	}
	else
	{
		timer->startTime = timer->stopTime;
		timer->stopTimeDelta = 0;
	}

	return;
}

// display time in seconds with 2 decimals
void displayTimer(TIMER *timer)
{
	if (timer->running)
	{
		ftime(&timer->currentBuffer);
		timer->currentTime = timer->currentBuffer.time * 1000 + timer->currentBuffer.millitm;
		printf("%6.2f", (timer->currentTime - timer->startTime)/1000.0);
	}
	else
		printf("%6.2f", (timer->stopTime - timer->startTime)/1000.0);

	return;
}

// display time in hh:mm:ss.dd
void displayTimerHMS(TIMER *timer)
{
	int hh, mm, ss;
	if (timer->running)
	{
		ftime(&timer->currentBuffer);
		timer->currentTime = timer->currentBuffer.time * 1000 + timer->currentBuffer.millitm;
		hh = (timer->currentTime - timer->startTime)/1000/3600;
		mm = ((timer->currentTime - timer->startTime)-hh*3600000)/1000/60;
		ss = ((timer->currentTime - timer->startTime)-hh*3600000-mm*60000)/1000;
		printf("%02d:%02d:%02d", hh, mm, ss);
	}
	else
	{
		hh = (timer->stopTime - timer->startTime)/1000/3600;
		mm = ((timer->stopTime - timer->startTime)-hh*3600000)/1000/60;
		ss = ((timer->stopTime - timer->startTime)-hh*3600000-mm*60000)/1000;
		printf("%02d:%02d:%02d", hh, mm, ss);
	}

	return;
}

// return time in milliseconds
U64 getMSTimer(TIMER *timer)
{
	if (timer->running)
	{
		ftime(&timer->currentBuffer);
		timer->currentTime = timer->currentBuffer.time * 1000 + timer->currentBuffer.millitm;
		return (timer->currentTime - timer->startTime) ;
	}
	else
		return (timer->stopTime - timer->startTime);
}

// return system time
U64 getSysMSTimer(TIMER *timer)
{
	ftime(&timer->currentBuffer);
	return (timer->currentBuffer.time * 1000 + timer->currentBuffer.millitm);
}
